<?php

//HTTP请求模块

namespace libs;

class HttpRequest
{
    public static function request($url, $params, $header = null, $method = 'GET')
    {
        $response = null;
        if ($url) {
            $method = strtoupper($method);
            if ($method == "GET") {
                if (is_array($params) and count($params)) {
                    if (strrpos($url, '?')) {
                        $url = $url . '&' . http_build_query($params);
                    } else {
                        $url = $url . '?' . http_build_query($params);
                    }

                    //创建连接
                    $ch = curl_init();

                    // 添加header信息
                    if ($header) {
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                    }

                    //增加HTTPS支持
                    if (strtoupper(substr($url, 0, 5)) == "HTTPS") {
                        date_default_timezone_set('PRC');
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                    }

                    // 执行请求
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_URL, $url);

                    $response = curl_exec($ch);

                }
            } elseif ($method == "POST") {
                if (is_array($params) and count($params)) {
                    //创建连接
                    $ch = curl_init();

                    // 添加header信息
                    if ($header) {
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                    }

                    //增加HTTPS支持
                    if (strtoupper(substr($url, 0, 5)) == "HTTPS") {
                        date_default_timezone_set('PRC');
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                    }

                    // 添加参数
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                    // 执行请求
                    curl_setopt($ch, CURLOPT_URL, $url);

                    $response = curl_exec($ch);

                }
            }

        } else {
            $response = "请求方式非法！";

        }
        return $response;
    }

}
